<!--
 * @Description:
 * @Author: ZachGmy
 * @Date: 2020-09-03 09:57:40
 * @LastEditors: ZachGmy
 * @LastEditTime: 2022-06-15 09:48:39
-->
<template>
  <div class="News">
    <!-- 顶部新增按钮 -->
    <div class="addUtton">
      <el-button class="addButton" type="primary" @click="toAddNews">增加</el-button>
    </div>
    <!-- 搜索框 -->
    <div class="searchArea">
       <!-- 搜索框 -->
        <el-select v-model="newsForm.categoryId" slot="prepend" placeholder="搜索新闻分类" clearable>
        <el-option :label="item.name" :value="item.id" v-for="item in allCategoryData" :key="item.id"></el-option>
    </el-select>
      <!-- 搜索按钮 -->
      <el-button type="primary" class="searchBtn" @click="getnewsInformation">搜索</el-button>
    </div>
    <!-- 表格内容展示区 -->
    <div class="newsInfomation">
      <el-table :data="newsInformation" style="width: 100%" max-width="50%">
        <!-- 序号 -->
        <el-table-column label="序号" width="120" type="index">
          <!-- <template slot-scope="scope" style="height: 30px">
            <span style="margin-left: 10px">{{ scope.$index + 1 }}</span>
          </template> -->
        </el-table-column>
        <!-- 新闻标题 -->
        <el-table-column prop="title" label="新闻标题" align="center">
        </el-table-column>
        <!-- 新闻分类 -->
        <el-table-column prop="category.name" label="新闻分类" width="120" align="center">
        </el-table-column>
        <!-- 发布时间 -->
        <el-table-column label="发布时间" width="160" align="center">
          <!-- 作用域插槽 -->
          <!-- scope.row选中的就是当前你要操作的这一行 -->
          <template slot-scope="scope">
            {{ scope.row.publishTime | fmtDate }}
          </template>
        </el-table-column>
        <!-- 操作 -->
        <el-table-column label="操作" width="140" align="center">
          <template slot-scope="scope">
            <el-button @click="toEditNews(scope.row)" type="text" size="small">修改</el-button>
            <el-button @click="toDelete(scope.row.id)" type="text" size="small">删除</el-button>
          </template>
        </el-table-column>

      </el-table>
    </div>

    <!-- 分页 -->
    <el-pagination @current-change="handleCurrentChange" :current-page.sync="page" :page-size="pageSize"
      layout="total, prev, pager, next" :total="total">
    </el-pagination>

    <!-- 模态框 -->
    <el-dialog v-if="dialogVisible" :title="dialogTitle" :visible.sync="dialogVisible" width="90%"
      :before-close="handleClose" lock-scroll>

      <!-- 表单区域 -->
      <!--  :model="ruleForm" 要提交给后端的表单对象 -->
      <!-- newsRules 表单验证规则 -->
      <!-- 通过ref找到当前的表单 -->
      <el-form :model="newsForm" :rules="newsRules" ref="newsForm" label-width="100px">
        <!-- 新闻标题 -->
        <el-form-item label="新闻标题" prop="title">
          <el-input v-model="newsForm.title"></el-input>
        </el-form-item>
        <!-- 下拉选择框 新闻分类 -->
        <el-form-item label="所属分类" prop="categoryId">
          <el-select v-model="newsForm.categoryId" placeholder="请选择所选所属分类">
            <el-option :label="item.name" :value="item.id" v-for="item in allCategoryData" :key="item.id"></el-option>
          </el-select>
        </el-form-item>
        <!-- 副文本编辑器 -->
        <el-form-item label="新闻内容" prop="content">
          <Tinymce v-model="newsForm.content" :height="200" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="toSubmitNews">确 定</el-button>
      </span>
    </el-dialog>


  </div>
</template>

<script>
import { get, post } from "@/utils/request"
//引入符文本编辑器 的组件
import Tinymce from '@/components/Tinymce'
export default {
  // 注册组件
  components: {
    Tinymce
  },
  data() {
    return {
      //新闻表单对象
      newsForm: {},
      // 新闻表单验证规则
      newsRules: {
        // 新闻标题
        title: [
          { required: true, message: '请输入新闻标题', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        // 所属分类
        categoryId: [
          { required: true, message: '请输入所属分类', trigger: 'change' },
        ]
      },
      // 新闻数组
      newsInformation: [],
      //所有新闻分类的数据
      allCategoryData: [],
      newsTime: "",
      // 
      page: 1,
      pageSize: 10,
      total: 10,
      //控制模态框的显示与隐藏  默认
      dialogVisible: false,
      dialogTitle: ""
    };
  },
  // 声明生命周期
  created() {
    this.getnewsInformation();
    this.getAllCategoryData();
  },
  methods: {
    // 获取所有新闻信息
    async getnewsInformation() {
      // 设置参数
      let params = {
        page: this.page,
        pageSize: this.pageSize,
        categoryId:this.newsForm.categoryId
      };
      //发送网络请求
      let res = await get("/article/pageQuery", params);
      // console.log(res.data.list)
      // 赋值
      this.newsInformation = res.data.list;
      //数据总条数
      this.total = res.data.total;
    },
    //搜索新闻分类
    async searchByCategoryId(){
       let params = {
        page: this.page,
        pageSize: this.pageSize,
        categoryId:this.newsForm.categoryId
      };
        let res = await get("/article/pageQuery", params);
      // console.log(res.data.list)
      // 赋值
      this.newsInformation = res.data.list;
      //数据总条数
      this.total = res.data.total;
    },
    //新增新闻
    toAddNews() {
      //设置模态框的标题
      this.dialogTitle = "发布新闻资讯 ";
      //清空表单对象中的数据
      this.newsForm = {}
      //弹出模态框
      this.dialogVisible = true;
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then(_ => {
          done();
        })
        .catch(_ => { });
    },
    // 编辑新闻
    toEditNews(row) {
      //设置模态框的标题
      this.dialogTitle = "修改新闻资讯 ";
      //将当前点击的这一行数据 赋值到模态框里
      this.newsForm = { ...row }
      //弹出模态框
      this.dialogVisible = true;
    },
    //删除新闻
    toDelete(id) {
      // 消息提示的确认
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        // 点击确定按钮执行的方法
        .then(async () => {
          // 发送请求
          let res = await get("/article/deleteById", { id });
          // console.log(res);
          if (res.status == 200) {
            // 请求成功给用户一个提示
            this.$message({
              type: "success",
              message: res.message,
            });
            // 刷新页面数据
            this.getnewsInformation();
          } else {
            this.$message({
              type: "error",
              message: "删除失败!",
            });
          }
        })
        // 点击取消按钮执行的方法
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 获取所有新闻的分类
    async getAllCategoryData() {
      let res = await get('/category/findAll')
      // console.log(res.data)
      this.allCategoryData = res.data
    },
    // 提交或修改新闻
    toSubmitNews() {
      console.log(this.newsForm)
      // 表单验证方法
      this.$refs['newsForm'].validate(async (valid) => {
        if (valid) {
          // 将表单对象提交到对应的接口中
          let res = await post('/article/saveOrUpdate', this.newsForm)
          if (res.status == 200) {
            // 成功提示
            this.$notify({
              title: '成功',
              message: res.message,
              type: 'success'
            });
            // 关闭模态框
            this.dialogVisible=false
            //刷新页面
            this.getnewsInformation()
          } else {
            // 失败提示
             this.$notify({
              title: '失败',
              message: res.data.message,
              type: 'error'
            });
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 分页
    handleCurrentChange(val) {
      //当前页码进行赋值 val 用户当前选中的那一页
      this.pagel = val;
      console.log(val);
      //再次调用获取数据的方法
      this.getnewsInformation();
    },
  },
}
</script>

<style scoped>
 /* 搜索框 */
.searchArea{
  margin-top: 5px;
}
</style>
